package com.atldy.commerce.config;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @version 1.0
 * @Author: lidongyang
 * @CreateTime: 2021-08-18 21:10
 * @Description： 异步任务线程池配置
 */
@Slf4j
@Configuration
@EnableAsync
public class AsyncExecutorConfig implements AsyncConfigurer {

    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数
        executor.setCorePoolSize(10);
        //最大线程数
        executor.setMaxPoolSize(20);
        //队列容量
        executor.setQueueCapacity(60);
        //线程存活时间
        executor.setKeepAliveSeconds(60);
        //线程前缀
        executor.setThreadNamePrefix("ldy-Async-");

        //等待所以任务执行完成关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //设置线程超时时间
        executor.setAwaitTerminationSeconds(60);
        //定义拒绝策率
        executor.setRejectedExecutionHandler(
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        //初始化线程池 ,初始化core线程
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandel();
    }

    class AsyncExceptionHandel implements AsyncUncaughtExceptionHandler {
        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
            //打印异常日志
            throwable.printStackTrace();
            log.error("async error:[{}] method name:[{}]  param:[{}]",
                    throwable.getMessage(), method.getName(), JSONUtil.formatJsonStr(
                            JSONUtil.toJsonStr(objects)
                    ));
            // TODO: 2021/8/18 生成环境可配置邮件、短信跑报警提醒

        }
    }
}